﻿var httpVerbs = {
    POST: 'POST',
    DEL: 'DELETE'
};
var photosDataService = (function () {
    var ds = {
        commit: function (type, url, data) {

            // Remove 'id' member to perpare for INSERT
            if (type === httpVerbs.POST) {
                delete data['photoId'];
            }

            return $.ajax({
                type: type,
                url: url,
                data: data,
                dataType: 'json'
            });
        },

        del: function (data) {
            return this.commit(httpVerbs.DEL, '/api/photos/' + data.photoId);
        },

        save: function (data) {

            var type = httpVerbs.POST,
                url = '/api/photos';

            return this.commit(type, url, data);
        },

        
        // reviver syntax: http://www.json.org/js.html
        parse: function (data) {
            var parseWithReviver = function (d) {
                return JSON.parse(d, function (key, value) {
                    var type;
                    if (value && typeof value === 'object') {
                        type = value.type;
                        if (typeof type === 'string' &&
                            typeof window[type] === 'function') {
                            return new (window[type])(value);
                        }
                    }
                    return value;
                });
            };

            var result = parseWithReviver(data);

            if (_.isArray(result)) {
                _.each(result, function (v, i) {
                    if (typeof v === 'string') {
                        result[i] = parseWithReviver(v);
                    }
                });
            }

            return result;
        },

        
    };

    _.bindAll(ds, 'del', 'save');

    return {
        save: ds.save,    
        del: ds.del,      
        parse: ds.parse       
    }


})();